package com.cl.code.common.utils;

import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.Map;

/**
 * YAML工具类
 * 用于从YAML文件中读取属性值
 *
 * @author chengliang
 * @since 1.0.0
 */
public class YamlUtils {

    /**
     * 从类路径资源中获取YAML属性值
     *
     * @param filePath     YAML文件路径
     * @param propertyPath 属性路径，如"spring.datasource.url"
     * @return 属性值
     */
    public static Object getProperty(String filePath, String propertyPath) {
        return getProperty(filePath, propertyPath, YamlUtils.class.getClassLoader());
    }

    /**
     * 从类路径资源中获取YAML属性值（指定ClassLoader）
     *
     * @param filePath     YAML文件路径
     * @param propertyPath 属性路径
     * @param classLoader  类加载器
     * @return 属性值
     */
    public static Object getProperty(String filePath, String propertyPath, ClassLoader classLoader) {
        try (InputStream input = classLoader.getResourceAsStream(filePath)) {
            return getProperty(input, propertyPath);
        } catch (Exception e) {
            throw new RuntimeException("Failed to read YAML file", e);
        }
    }

    /**
     * 从输入流中获取YAML属性值
     *
     * @param input        YAML文件输入流
     * @param propertyPath 属性路径
     * @return 属性值
     */
    public static Object getProperty(InputStream input, String propertyPath) {
        Yaml yaml = new Yaml();
        Map<String, Object> yamlProps = yaml.load(input);
        return getProperty(yamlProps, propertyPath);
    }

    /**
     * 从已加载的YAML Map中获取属性值
     *
     * @param yamlProps    YAML Map
     * @param propertyPath 属性路径
     * @return 属性值
     */
    public static Object getProperty(Map<String, Object> yamlProps, String propertyPath) {
        String[] keys = propertyPath.split("\\.");
        Object value = yamlProps;

        for (String key : keys) {
            if (value instanceof Map) {
                value = ((Map<?, ?>) value).get(key);
            } else {
                return null;
            }
        }

        return value;
    }
}